package com.firewolf.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.firewolf.dto.pojo.Student;
import com.firewolf.dto.primarykeyclass.PrimaryKey;
import com.firewolf.dto.primarykeyclass.Student2;


public class MainDriver {

	private SessionFactory factory;
	
	private Session session;
	
	private Transaction transaction;
	
	
	@Test
	public void testType(){
		openSession();
		
		Student s = new Student();
		s.setCardID("3237");
		s.setAge(23);
		s.setName("dad");
		session.save(s);
		
		closeSession();
	}
	
	@Test
	public void testType2(){
		openSession();
		
		Student2 s = new Student2();
		s.setAge(23);
		PrimaryKey k = new PrimaryKey();
		k.setCardID("12");
		k.setName("dad");
		s.setPrimaryKey(k);
		session.save(s);
		
		closeSession();
	}
	
	
	@Before
	public void init() {
		Configuration cfg = new Configuration().configure();

		ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
				.buildServiceRegistry();
		factory = cfg.buildSessionFactory(registry);
	}

	@After
	public void destory() {
		factory.close();
	}
	
	private void openSession(){
		session = factory.openSession();
		transaction = session.beginTransaction();
	}
	
	private void closeSession(){
		transaction.commit();
		session.close();
	}

}
